package com.rsa.decrypt.sign;

import com.rsa.tools.RsaTools;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author lf
 * @Description: 验签
 * @date 2020/7/30 12:40
 */
public class ValiditySign {

    private static final Logger log = LoggerFactory.getLogger(ValiditySign.class);

    /**
     * 验签
     * @param srcData 原始字符串
     * @param otherPublicKey 公钥
     * @param sign 签名
     * @return 是否验签通过
     */
    public static boolean dataVerify(String srcData, String otherPublicKey, String sign) throws Exception {
        log.info("对外提供的验签方法....");
        return verify(srcData, RsaTools.getPublicKey(otherPublicKey), sign);
    }

    /**
     * 验签
     *
     * @param srcData 原始字符串
     * @param publicKey 公钥
     * @param sign 签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }
}
